package net.acnull.arpg.listeners;

import net.acnull.arpg.kill.KillNumberHelper;
import net.acnull.arpg.rpg.AbstractRPG;
import net.acnull.arpg.rpg.RPGManager;
import net.acnull.arpg.rpg.potion.Potion;
import net.acnull.arpg.rpg.potion.PotionManager;
import net.acnull.arpg.rpg.skill.IDeath;
import net.acnull.arpg.rpg.skill.Skill;
import net.acnull.arpg.rpg.skill.Skillable;
import org.bukkit.attribute.Attribute;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.List;

public class DeathListener implements Listener {
    @EventHandler
    public void onDeath(EntityDeathEvent event){
        for(Potion potion: PotionManager.getInstance().getPotionsByEntity(event.getEntity())){
            potion.onDie();
            PotionManager.getInstance().removePotion(potion);
        }
        if(event.getEntity().getKiller()==null){
            return;
        }
        ItemStack item=event.getEntity().getKiller().getEquipment().getItemInMainHand();
        if(item!=null&&item.hasItemMeta()&&item.getItemMeta().hasLore()){
            AbstractRPG rpg= RPGManager.getInstance().getRPGByFirstLore(item.getItemMeta().getLore().get(0));
            if(rpg instanceof Skillable){
                Skill skill=((Skillable)rpg).getSkill();
                if(skill instanceof IDeath) {
                    ((IDeath) skill).onDeath(event.getEntity());
                }
            }
            if(event.getEntity().getCustomName()!=null&&event.getEntity().getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()>25) {
                for(int i=0;i<item.getItemMeta().getLore().size();i++) {
                    String lore=item.getItemMeta().getLore().get(i);
                    KillNumberHelper helper = KillNumberHelper.parseString(lore);
                    if (helper == null) {
                        continue;
                    }
                    if(helper.getLevel()-1<helper.getMaxLevel()){
                        helper.setLevel(helper.getLevel()+1);
                    }else{
                        break;
                    }
                    ItemMeta meta=item.getItemMeta();
                    List<String> list=meta.getLore();
                    list.set(i,helper.toString());
                    meta.setLore(list);
                    item.setItemMeta(meta);
                    break;
                }
            }
        }
    }
}
